package interfaces.ltu;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.util.FloatMath;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.ZoomControls;


import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;

public class DisplayLocationActivity01 extends Activity implements OnTouchListener{

	EditText inputUrl;
	String myAddress;
	String ServerIPAddress="130.240.97.175";
	public ImageView imgView;
	public float scaleWidth, scaleHeight;
	public float zoom = 0.0f;
	public int  screenWidth=0;
	// Matrix instances to move and zoom image
	Matrix matrix = new Matrix();
	Matrix eventMatrix = new Matrix();
	// possible touch states
	final static int NONE = 0;
	final static int DRAG = 1;
	final static int ZOOM = 2;
	int touchState = NONE;
	final static float MIN_DIST = 50;
	static float eventDistance = 0;
	static float centerX =0, centerY = 0;
	
	OnClickListener getImageBtnOnClick = new OnClickListener() {
		public void onClick(View view) {
			/*Context context = view.getContext();
			Editable ed = inputUrl.getText();
			Drawable image = ImageOperations(context, ed.toString(),"image.jpg");
			imgView = new View(context);*/
			
			ServerCom sc =new ServerCom();
			sc.execute("s");
			//imgView.setBackgroundDrawable(image);
			
			
			ZoomControls myImageControllers= (ZoomControls)findViewById(R.id.zoomControls1);
			myImageControllers.setOnZoomInClickListener(new View.OnClickListener() {
	              
	                public void onClick(View v) {
                        //v= imgView;
                        System.out.println("ZoomIN");
                        ZoomIn();
	                }});
			myImageControllers.setOnZoomOutClickListener(new View.OnClickListener() {
	              
	                public void onClick(View v) {
	                      //v= imgView;
	                      System.out.println("ZoomOut");
	                      ZoomOut();
	                }
	        });
		}
	};

	/** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.displaylocationbuttonmain);
        imgView = (ImageView) findViewById(R.id.image1);// this is for inst.
		imgView.setOnTouchListener(this);
         //Request window features before setContentView
		//requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		// Set the layout resource to use for the custom title
		//setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
				//R.drawable.ltu_logo);
	
		inputUrl = ((EditText) findViewById(R.id.imageUrl));// this is for inst.
		inputUrl.setSingleLine();
		inputUrl.setTextSize(11);
		
        ImageButton next = (ImageButton) findViewById(R.id.DisplayLocationbackButton);
        next.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent intent = new Intent();
                setResult(RESULT_OK, intent);
                finish();
            }

        });
    
		Button getImageButton = (Button) findViewById(R.id.getImageButton);// this
		// too
		getImageButton.setOnClickListener(getImageBtnOnClick);

		final Spinner roomListSpinner = (Spinner) findViewById(R.id.spinner1);

		List<String> roomNumberList = new ArrayList<String>();

		roomNumberList.add("A-1510");
		roomNumberList.add("A-1509");
		roomNumberList.add("A-1508");
		roomNumberList.add("A-1507");
		roomNumberList.add("A-1506");

		ArrayAdapter<String> aspnMusketeers = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, roomNumberList);

		aspnMusketeers
		.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		roomListSpinner.setAdapter(aspnMusketeers);

		// Set up a callback for the spinner
		roomListSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onNothingSelected(AdapterView<?> arg0) {
			}

			public void onItemSelected(AdapterView<?> parent, View v,
					int position, long id) {
				// Code that does something when the Spinner room number is
				// changed
				int position0 = 0;
				int position1 = 1;
				int position2 = 2;
				int position3 = 3;
				int position4 = 4;

				if (position4 == roomListSpinner.getSelectedItemPosition()) {
					myAddress = "http://bishopsworth.wikispaces.com/file/view/Planets_shirt_2_large.jpg/52134137/Planets_shirt_2_large.jpg";

				}
				if (position3 == roomListSpinner.getSelectedItemPosition()) {
					myAddress = "http://spaceplace.nasa.gov/planet-weather/8_planets.en.jpg";

				}
				if (position2 == roomListSpinner.getSelectedItemPosition()) {
					myAddress = "http://www.manatee.k12.fl.us/sites/elementary/samoset/psgk3ex_files/Neptune.gif";

				}
				if (position1 == roomListSpinner.getSelectedItemPosition()) {
					myAddress = " http://upload.wikimedia.org/wikipedia/commons/thumb/3/3e/1e7m_comparison_Uranus_Neptune_Sirius_B_Earth_Venus.png/300px-1e7m_comparison_Uranus_Neptune_Sirius_B_Earth_Venus.png";

				}
				if (position0 == roomListSpinner.getSelectedItemPosition()) {
					myAddress = " http://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Exoplanet_Comparison_HR_8799_c.png/320px-Exoplanet_Comparison_HR_8799_c.png";

				}

			}
			//
		});
	}

	private Drawable ImageOperations(Context ctx, String url,
			String saveFilename) {
		try {
			InputStream is = (InputStream) this.fetch(url);
			Drawable d = Drawable.createFromStream(is, "src");
			return d;
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	public Object fetch(String address) throws MalformedURLException,
	IOException {
		// myAddress="http://image.gsfc.nasa.gov/image/image_launch_a5.jpg";
		address = myAddress;
		URL url = new URL(address);
		Object content = url.getContent();
		return content;
	}

	public class ServerCom extends AsyncTask<String, Integer, Bitmap>{

		@Override
		protected Bitmap doInBackground(String... arg0) {
			// TODO Auto-generated method stub
			Bitmap bmp = null;
			Socket socket= null;
			try {
				
				socket= new Socket(ServerIPAddress,8890);
				
				ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
			
				byte[] buffer;
				try {
					
					buffer = (byte[])ois.readObject();
					//FileOutputStream fos = new FileOutputStream("/sdcard/tlogo1.jpg");
					//fos.write(buffer);
					//fos.close();
					
					 bmp=BitmapFactory.decodeByteArray(buffer,0,buffer.length);
					//ImageView image=new ImageView(this);
			        // icon.setImageBitmap(bmp);
			        
					 socket.close();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return bmp;
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			//((ImageView) imgView).setImageBitmap(result);
			//float scaleWidth, scaleHeight;
			Display display = getWindowManager().getDefaultDisplay(); 
			screenWidth = display.getWidth();
			//int screenHeight = display.getHeight();
			ShowImage(result);
			/*float imageWidth = (float)result.getWidth();
			float imageHeight = (float)result.getHeight();
			float newHeight = imageHeight / (imageWidth / screenWidth);
			float newWidth = screenWidth;
			scaleWidth = screenWidth / imageWidth;
			scaleHeight = newHeight / imageHeight;
			imgView.setImageBitmap(result);
			Matrix mtrx = new Matrix();
			mtrx.postScale(scaleWidth, scaleHeight);
			imgView.setImageMatrix(mtrx);
			imgView.setScaleType(ScaleType.MATRIX);
			imgView.invalidate();*/
		}

	}
	void ShowImage(Bitmap cur_bm) {
		//Bitmap cur_bm = BitmapFactory.decodeFile(path);
		float imageWidth = (float)cur_bm.getWidth();
		float imageHeight = (float)cur_bm.getHeight();
		float newHeight = imageHeight / (imageWidth / screenWidth);
		float newWidth = screenWidth;
		scaleWidth = screenWidth / imageWidth;
		scaleHeight = newHeight / imageHeight;
		imgView.setImageBitmap(cur_bm);
		SetImageMatrix();

	}
	
	void SetImageMatrix() {
		Matrix mtrx = new Matrix();
		mtrx.postScale(scaleWidth, scaleHeight);
		imgView.setImageMatrix(mtrx);
		imgView.setScaleType(ScaleType.MATRIX);
		imgView.invalidate();

		}

		void ZoomIn() {
		zoom += 0.01;
		scaleWidth += zoom;
		scaleHeight += zoom;
		System.out.println("ZoomIn  scaleWidth:"+scaleWidth+" scaleHeight:"+scaleHeight+ " zoom:"+zoom);
		SetImageMatrix();

		}

		void ZoomOut() {
		zoom -= 0.01;
		scaleWidth -= zoom;
		scaleHeight -= zoom;
		System.out.println("ZoomOut scaleWidth:"+scaleWidth+" scaleHeight:"+scaleHeight+ " zoom:"+zoom);
		SetImageMatrix();
		} 

	
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		System.out.println(event.toString());
		ImageView view = (ImageView) v;
		switch (event.getAction() & MotionEvent.ACTION_MASK) {
		case MotionEvent.ACTION_DOWN:
			//primary touch event starts: remember touch down location
			System.out.println("ACTION_DOWN");
			touchState = DRAG;
			centerX = event.getX(0);
			centerY = event.getY(0);
			eventMatrix.set(matrix);
			break;
		case MotionEvent.ACTION_POINTER_DOWN:
		//secondary touch event starts: remember distance and center
			/*System.out.println("ACTION_POINTER_DOWN");
			eventDistance = calcDistance(event);
			calcMidpoint(centerX, centerY, event);
			if (eventDistance > MIN_DIST) {
				eventMatrix.set(matrix);
				touchState = ZOOM;
			}*/
		break;
		case MotionEvent.ACTION_MOVE:
			System.out.println("ACTION_MOVE");
			if (touchState == DRAG) {
			//single finger drag, translate accordingly
				matrix.set(eventMatrix);
				matrix.setTranslate(event.getX(0) - centerX,event.getY(0) - centerY);
				System.out.println("event.getX(0):"+event.getX(0)+" centerX:"+centerX+" event.getX(0) - centerX:"+(event.getX(0) - centerX)+" event.getY(0) - centerY:"+(event.getY(0) - centerY));
			} else if (touchState == ZOOM) {
			//multi-finger zoom, scale accordingly around center
				/*float dist = calcDistance(event);
				if (dist > MIN_DIST) {
					matrix.set(eventMatrix);
					float scale = dist / eventDistance;
					matrix.postScale(scale, scale, centerX, centerY);
				}*/
			}
			// Perform the transformation
			view.setImageMatrix(matrix);
			break;
		case MotionEvent.ACTION_UP:
		case MotionEvent.ACTION_POINTER_UP:
			touchState = NONE;
			break;
		}
		return true;
	}
	private float calcDistance(MotionEvent event) {
		float x = event.getX(0) - event.getX(1);
		float y = event.getY(0) - event.getY(1);
		return FloatMath.sqrt(x * x + y * y);
	}
		private void calcMidpoint(float centerX, float centerY,
		MotionEvent event) {
		centerX = (event.getX(0) + event.getX(1))/2;
		centerY = (event.getY(0) + event.getY(1))/2;
	}

}
